<template>
  <div class="home">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>签到列表</span>
      </div>
      <el-table :data="attendanceList" style="width: 100%">
        <el-table-column prop="classroomName" label="班级" width="120"></el-table-column>
        <el-table-column prop="teacherName" label="教师" width="120"></el-table-column>
        <el-table-column prop="type" label="签到类型" width="120">
          <template slot-scope="scope">
            <el-tag :type="getTypeTag(scope.row.type)">
              {{ getTypeText(scope.row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="startTime" label="开始时间" width="180"></el-table-column>
        <el-table-column prop="endTime" label="结束时间" width="180"></el-table-column>
        <el-table-column prop="studentStatus" label="签到状态" width="120">
          <template slot-scope="scope">
            <el-tag :type="getStatusTag(scope.row.studentStatus)">
              {{ getStatusText(scope.row.studentStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.status === 1 && scope.row.studentStatus === 0"
              type="primary"
              size="mini"
              @click="showSignDialog(scope.row)">
              签到
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 签到对话框 -->
    <el-dialog :title="'签到 - ' + currentTask.classroomName" :visible.sync="signDialogVisible" width="30%">
      <!-- 一键签到 -->
      <div v-if="currentTask.type === 'NORMAL'">
        <el-button type="primary" @click="handleQuickSign">一键签到</el-button>
      </div>

      <!-- 签到码签到 -->
      <div v-if="currentTask.type === 'CODE'">
        <el-input v-model="signCode" placeholder="请输入签到码"></el-input>
        <el-button type="primary" @click="handleCodeSign" style="margin-top: 10px;">确认签到</el-button>
      </div>

      <!-- 位置签到 -->
      <div v-if="currentTask.type === 'LOCATION'">
        <div>当前位置：{{ currentLocation.address || '正在获取位置...' }}</div>
        <el-button type="primary" @click="handleLocationSign" style="margin-top: 10px;">确认签到</el-button>
      </div>

      <!-- 手势签到 -->
      <div v-if="currentTask.type === 'GESTURE'">
        <div class="gesture-grid">
          <div v-for="i in 9" :key="i"
               class="gesture-point"
               :class="{ active: gestureSequence.includes(i.toString()) }"
               @click="handleGesturePointClick(i)">
            {{ i }}
          </div>
        </div>
        <div class="gesture-sequence">绘制顺序：{{ gestureSequence }}</div>
        <el-button type="primary" @click="handleGestureSign" style="margin-top: 10px;">确认签到</el-button>
      </div>

      <!-- 二维码签到 -->
      <div v-if="currentTask.type === 'QR_CODE'">
        <el-upload
          class="upload-demo"
          action="#"
          :auto-upload="false"
          :on-change="handleQRCodeUpload">
          <el-button slot="trigger" size="small" type="primary">选取二维码图片</el-button>
        </el-upload>
        <el-button type="primary" @click="handleQRCodeSign" style="margin-top: 10px;">确认签到</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'Home',
  data() {
    return {
      attendanceList: [],
      signDialogVisible: false,
      currentTask: {},
      signCode: '',
      currentLocation: {
        latitude: 0,
        longitude: 0,
        address: ''
      },
      gestureSequence: '',
      qrCode: ''
    }
  },
  created() {
    this.fetchAttendanceList()
  },
  methods: {
    async fetchAttendanceList() {
      try {
        const response = await axios.get('http://localhost:8080/api/student/attendance/tasks')
        if (response.data.code === 1) {
          this.attendanceList = response.data.data
        }
      } catch (error) {
        console.error('获取签到列表失败:', error)
      }
    },
    getTypeTag(type) {
      const typeMap = {
        'CODE': 'success',
        'GESTURE': 'warning',
        'QR_CODE': 'info',
        'LOCATION': 'danger',
        'NORMAL': 'primary'
      }
      return typeMap[type] || 'info'
    },
    getTypeText(type) {
      const typeMap = {
        'CODE': '签到码',
        'GESTURE': '手势',
        'QR_CODE': '二维码',
        'LOCATION': '位置',
        'NORMAL': '一键'
      }
      return typeMap[type] || type
    },
    getStatusTag(status) {
      const statusMap = {
        0: 'info',
        1: 'success',
        2: 'danger'
      }
      return statusMap[status] || 'info'
    },
    getStatusText(status) {
      const statusMap = {
        0: '未签到',
        1: '已签到',
        2: '缺勤'
      }
      return statusMap[status] || '未知'
    },
    showSignDialog(task) {
      this.currentTask = task
      this.signDialogVisible = true
      this.signCode = ''
      this.gestureSequence = ''
      this.qrCode = ''

      if (task.type === 'LOCATION') {
        this.getCurrentLocation()
      }
    },
    async handleQuickSign() {
      try {
        const response = await axios.post('http://localhost:8080/api/student/attendance/quick', {
          taskId: this.currentTask.id
        }, {
          headers: {
            'token': localStorage.getItem('token')
          }
        })
        if (response.data.code === 1) {
          this.$message.success('签到成功')
          this.signDialogVisible = false
          this.fetchAttendanceList()
        } else {
          this.$message.error(response.data.msg || '签到失败')
        }
      } catch (error) {
        console.error('一键签到失败:', error)
        this.$message.error('签到失败')
      }
    },
    async handleCodeSign() {
      if (!this.signCode) {
        this.$message.warning('请输入签到码')
        return
      }
      try {
        const response = await axios.post('http://localhost:8080/api/student/attendance/code', {
          taskId: this.currentTask.id,
          code: this.signCode
        }, {
          headers: {
            'token': localStorage.getItem('token')
          }
        })
        if (response.data.code === 1) {
          this.$message.success('签到成功')
          this.signDialogVisible = false
          this.fetchAttendanceList()
        } else {
          this.$message.error(response.data.msg || '签到失败')
        }
      } catch (error) {
        console.error('签到码签到失败:', error)
        this.$message.error('签到失败')
      }
    },
    async getCurrentLocation() {
      try {
        const position = await new Promise((resolve, reject) => {
          navigator.geolocation.getCurrentPosition(resolve, reject)
        })
        this.currentLocation.latitude = position.coords.latitude
        this.currentLocation.longitude = position.coords.longitude

        // 这里可以调用地图API获取具体地址
        this.currentLocation.address = '正在获取地址...'
      } catch (error) {
        console.error('获取位置失败:', error)
        this.$message.error('获取位置失败，请检查定位权限')
      }
    },
    async handleLocationSign() {
      try {
        const response = await axios.post('http://localhost:8080/api/student/attendance/location', {
          taskId: this.currentTask.id,
          latitude: this.currentLocation.latitude,
          longitude: this.currentLocation.longitude
        }, {
          headers: {
            'token': localStorage.getItem('token')
          }
        })
        if (response.data.code === 1) {
          this.$message.success('签到成功')
          this.signDialogVisible = false
          this.fetchAttendanceList()
        } else {
          this.$message.error(response.data.msg || '签到失败')
        }
      } catch (error) {
        console.error('位置签到失败:', error)
        this.$message.error('签到失败')
      }
    },
    handleGesturePointClick(point) {
      if (!this.gestureSequence.includes(point.toString())) {
        this.gestureSequence += point.toString()
      }
    },
    async handleGestureSign() {
      if (this.gestureSequence.length < 4) {
        this.$message.warning('请至少绘制4个点')
        return
      }
      try {
        const response = await axios.post('http://localhost:8080/api/student/attendance/gesture', {
          taskId: this.currentTask.id,
          gestureSequence: this.gestureSequence
        }, {
          headers: {
            'token': localStorage.getItem('token')
          }
        })
        if (response.data.code === 1) {
          this.$message.success('签到成功')
          this.signDialogVisible = false
          this.fetchAttendanceList()
        } else {
          this.$message.error(response.data.msg || '签到失败')
        }
      } catch (error) {
        console.error('手势签到失败:', error)
        this.$message.error('签到失败')
      }
    },
    handleQRCodeUpload(file) {
      // 这里需要实现二维码图片识别
      // 可以使用第三方库如 jsQR 来识别二维码
      this.qrCode = '识别出的二维码内容'
    },
    async handleQRCodeSign() {
      if (!this.qrCode) {
        this.$message.warning('请先上传二维码图片')
        return
      }
      try {
        const response = await axios.post('http://localhost:8080/api/student/attendance/qrcode', {
          taskId: this.currentTask.id,
          qrCode: this.qrCode
        }, {
          headers: {
            'token': localStorage.getItem('token')
          }
        })
        if (response.data.code === 1) {
          this.$message.success('签到成功')
          this.signDialogVisible = false
          this.fetchAttendanceList()
        } else {
          this.$message.error(response.data.msg || '签到失败')
        }
      } catch (error) {
        console.error('二维码签到失败:', error)
        this.$message.error('签到失败')
      }
    }
  }
}
</script>

<style scoped>
.home {
  padding: 20px;
}
.box-card {
  margin-bottom: 20px;
}
.gesture-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 10px;
  margin: 20px 0;
}
.gesture-point {
  width: 60px;
  height: 60px;
  border: 2px solid #dcdfe6;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  cursor: pointer;
  transition: all 0.3s;
}
.gesture-point.active {
  background-color: #409EFF;
  color: white;
  border-color: #409EFF;
}
.gesture-sequence {
  margin: 10px 0;
  font-size: 16px;
}
</style>
